package com.ems.servlet;

import com.ems.dao.EmployeeDAO;
import com.ems.model.Employee;
import com.ems.model.User;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/profile")
public class ProfileServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        HttpSession session = request.getSession();
        Employee employee = (Employee) session.getAttribute("employee");

        // 如果session中没有员工信息，尝试重新获取
        if (employee == null) {
            User user = (User) session.getAttribute("user");
            if (user != null && "employee".equals(user.getRole())) {
                try {
                    EmployeeDAO dao = new EmployeeDAO();
                    employee = dao.getEmployeeById(user.getUserId());
                    session.setAttribute("employee", employee);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        if (employee != null) {
            RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/admin/profile.jsp");
            dispatcher.forward(request, response);
        } else {
            response.sendRedirect("login.jsp");
        }
    }
}